package com.tiennt.android.droidcamreader;

import android.app.AlertDialog;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class CameraActivityHandler extends Handler {
	public static final int NO_INTERNET_CONNECTION = 1;
	public static final int MSG_WCODE_OCR_INIT_FAILED = 2;
	public static final int MSG_WCODE_OCR_INIT_SUCCESS = 3;
	public static final int MSG_WCODE_DO_OCR = 4;
	public static final int MSG_WCODE_OCR_FAILED = 5;
	public static final int MSG_WCODE_OCR_RESULT_DELIVERY = 6;
	public static final int MSG_WCODE_TRANSLATE_FAILED = 7;
	public static final int MSG_WCODE_TRANSLATE_DELIVERY = 8;

	public CameraActivity mCamActivity;

	public CameraActivityHandler(CameraActivity activity) {
		mCamActivity = activity;
	}

	@Override
	public void handleMessage(Message msg) {
		// TODO Auto-generated method stub
		super.handleMessage(msg);
		switch (msg.what) {
		case MSG_WCODE_OCR_INIT_FAILED:
			String message = (String) msg.obj;
			AlertDialog.Builder alert = new AlertDialog.Builder(mCamActivity)
					.setTitle("Initial failed").setMessage(message)
					.setPositiveButton("OK", null);

			AlertDialog dialog = alert.create();
			dialog.show();

			Button btnOK = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
			btnOK.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					mCamActivity.finish();
				}
			});
			break;
		case MSG_WCODE_OCR_INIT_SUCCESS:
			mCamActivity.showControlsAndCropView();
			break;
		case MSG_WCODE_DO_OCR:
			new OcrAsyncTask(mCamActivity, (byte[]) msg.obj, msg.arg1, msg.arg2)
					.execute();
			break;
		case MSG_WCODE_OCR_FAILED:
			Toast.makeText(mCamActivity,
					"OCR failed.\n" + (String) msg.obj,
					Toast.LENGTH_LONG).show();
			break;
		case MSG_WCODE_OCR_RESULT_DELIVERY:
			mCamActivity.showOneShotResult((OcrResult) msg.obj);
			new TranslatorAsyncTask(mCamActivity, this)
					.execute(((OcrResult) msg.obj).getText());
			break;
		case MSG_WCODE_TRANSLATE_DELIVERY:
			mCamActivity.onTranslateResultDelivery((String) msg.obj);
			break;
		case MSG_WCODE_TRANSLATE_FAILED:
			Toast.makeText(mCamActivity,
					"Translate failed.\n" + ((Exception) msg.obj).getMessage(),
					Toast.LENGTH_LONG).show();
		default:
			break;
		}
	}

}
